from db_module import *
from common import *
from google.appengine.ext import webapp

class VotePage(webapp.RequestHandler):
  def get(self):
        check_user(self)
        username = get_username()
        self.response.out.write('<html><body><a href="/">Back to home</a><br />')
        if is_admin():
            self.response.out.write("""<a href="../voteadmin">Vote Admin Page</a><br/>""")
        topics = Topic.all()
        i = 0
        for topic in topics:
            self.response.out.write('<b>%s</b></br>' % topic.question)
            user_topics = User_Topic.gql("where username = :1 and topic = :2", username, Topic.key(topic).id())
            if user_topics.count() > 0:
                self.response.out.write("""<div id="chart_div_%d"></div>""" % i)
                self.response.out.write("""
                    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
                    <script type="text/javascript">
                      google.load("visualization", "1", {packages:["corechart"]});
                      google.setOnLoadCallback(drawChart);
                      function drawChart() {
                        var data = new google.visualization.DataTable();
                        data.addColumn('string', 'Choices');
                        data.addColumn('number', 'Votes');
                        data.addRows([""")
                answers = topic.answers.order('answer_order')
                for answer in answers:
                    self.response.out.write("['%s', " % answer.answer_desc)
                    self.response.out.write("%d]," % answer.votes)
                self.response.out.write("""]);
                        var options = {
                          width: 450, height: 300,
                          title: '%s'
                        };""" % topic.question)
                
                self.response.out.write("""var chart = new google.visualization.%s(""" % topic.chart_type)
                self.response.out.write("""document.getElementById('chart_div_%d'));
                        chart.draw(data, options);
                      }
                    </script>""" % i)
            else:
                self.response.out.write("Please select one of the following to voted<br />")
                self.response.out.write("""<form action="/vote" method="post">""")
                self.response.out.write("""<input type="hidden" name="question_id" value="%d"/>""" % Topic.key(topic).id())
                answers = topic.answers.order('answer_order')
                for answer in answers:
                    if topic.sigle_choice:
                        self.response.out.write("""<input type="radio" """)
                    else:
                        self.response.out.write("""<input type="checkbox" """)
                    self.response.out.write("""name="answer_%d" """ % Topic.key(topic).id())
                    self.response.out.write(""" value="%d" />""" % Answer.key(answer).id())
                    self.response.out.write(""" %s<br />""" % answer.answer_desc)
                                       
                self.response.out.write("""<input type="submit" name="vote" value="Vote">""")
                self.response.out.write("""</form>""")
            i = i + 1
        self.response.out.write('</body></html>')
    
  def post(self):
    if self.request.get('vote'):
        topic_id = int(self.request.get('question_id'))
        topic = Topic.get_by_id(topic_id)
        all_answer_desc = ""
        if topic.sigle_choice:
            qids = self.request.get('answer_%s' % self.request.get('question_id'))
        else:
            qids = self.request.get_all('answer_%s' % self.request.get('question_id'))
        if qids:
            if topic.sigle_choice:
                answer = Answer.get_by_id(int(qids))
                answer.votes = answer.votes + 1
                answer.save()
                all_answer_desc = answer.answer_desc
            else:
                for qid in qids:
                    answer = Answer.get_by_id(int(qid))
                    answer.votes = answer.votes + 1
                    answer.save()    
                    all_answer_desc += " / " + answer.answer_desc
            user_topic = User_Topic()
            user_topic.username = get_username()
            user_topic.choice = all_answer_desc
            user_topic.topic = Topic.key(topic).id()
            user_topic.save()
    self.redirect('/vote')

class VoteAdmin(webapp.RequestHandler):
    def get(self):
        check_is_admin(self, '/vote')
        self.response.out.write("""
            <form action="/voteadmin" method="post">
            New Topic:
            <div><input name="txt_newtopic"/>
                <select name="chart_type">                   
                  <option value="PieChart">Pie Chart</option>
                  <option value="LineChart">Line Chart</option>
                  <option value="ColumnChart">Column Chart</option>
                </select>
            </div>
            <div><input type="submit" name="newtopic" value="Create"></div>
            </form><hr />""")
        topics = Topic.all()
        for topic in topics:
            self.response.out.write("""<form action="/voteadmin" method="post"><input type="hidden" name="topic_id" value="%d" />""" % Topic.key(topic).id())
            self.response.out.write("""<b><input name="txt_question" value="%s"/></b>""" % topic.question)
            self.response.out.write("""<select name="chart_type">""")
            if topic.chart_type == "PieChart":                   
                self.response.out.write("""<option value="PieChart" selected="selected">Pie Chart</option>""")
            else:
                self.response.out.write("""<option value="PieChart">Pie Chart</option>""")
            if topic.chart_type == "LineChart":                   
                self.response.out.write("""<option value="LineChart" selected="selected">Line Chart</option>""")
            else:
                self.response.out.write("""<option value="LineChart">Line Chart</option>""")
            if topic.chart_type == "ColumnChart":                   
                self.response.out.write("""<option value="ColumnChart" selected="selected">Column Chart</option>""")
            else:
                self.response.out.write("""<option value="ColumnChart">Column Chart</option>""")
            self.response.out.write("""</select>""")
            self.response.out.write("""<input type="checkbox" name="is_sigle_choice" """)
            if topic.sigle_choice:
                  self.response.out.write(""" checked="checked" """)
            self.response.out.write("""/>""")
            self.response.out.write("""<input type="submit" name="changetopic" value="Save changes">""")    
            self.response.out.write("""<input type="submit" name="removetopic" value="Delete Topic"><br /><br />""") 
            if topic.answers.count()>0:
                answers = topic.answers.order('answer_order')
                for answer in answers:
                    self.response.out.write("""<input type="checkbox" name="del_answers" value="%d" """ % Answer.key(answer).id())
                    self.response.out.write(""">%s<br />""" % answer.answer_desc)
            self.response.out.write("""<input type="submit" name="removeanswer" value="Delete Answer"><br /><br />""")    
            self.response.out.write("""<input type="textbox" name="txt_newanswer"><br />""")    
            self.response.out.write("""<input type="submit" name="newanswer" value="New Answer"><br /><br />""")

            self.response.out.write("</form>")
            self.response.out.write("<hr />")
            
    def post(self):
        check_is_admin(self, '/vote')
        if self.request.get('changetopic'):
            topic = Topic.get_by_id(int(self.request.get('topic_id')))
            topic.question = self.request.get('txt_question')
            topic.chart_type = self.request.get('chart_type')
            Topic.sigle_choice = bool(self.request.get('is_sigle_choice'))
            topic.save()
        elif self.request.get('newanswer'):
            answer = Answer()
            answer.answer_desc = self.request.get('txt_newanswer')
            answer.votes = 0
            topic = Topic.get_by_id(int(self.request.get('topic_id')))
            answer.topic_id = topic.key()
            if topic.answers.get():
                max_answer = topic.answers.order("-answer_order").get()
                answer.answer_order = max_answer.answer_order + 1
            else:
                answer.answer_order = 0
            answer.put()
        elif self.request.get('newtopic'):
            topic = Topic()
            topic.question = self.request.get('txt_newtopic')
            topic.chart_type = self.request.get('chart_type')
            topic.sigle_choice = True
            topic.put()
        elif self.request.get('removeanswer'):
            answer_ids = self.request.get_all('del_answers')
            for answer_id in answer_ids:
                answer = Answer.get_by_id(int(answer_id))
                answer.remove()
        elif self.request.get('removetopic'):
            topic_id = self.request.get('topic_id')
            topic = Topic.get_by_id(int(topic_id))
            answers = topic.answers
            for answer in answers:
                answer.remove()
            topic.remove()
        self.redirect('/voteadmin')    
